package main

import (
	"database/sql"
	"fmt"
	_ "github.com/go-sql-driver/mysql"
	"github.com/pkg/errors"
)

/*
 sql.ErrNoRows 这个错误并非是影响程序执行的错误， find 函数中能可以自行处理。
*/
func main() {
	row, err := find(1)
	if err != nil {
		fmt.Printf("find err %+v", err)
		return
	}
	if row == nil {
		//nothing
		return
	}
	//do something
	fmt.Println(row)

}

type User struct {
	Id   int
	Name string
	Age  int
}

func find(id int) (*User, error) {
	db, err := sql.Open("mysql", "root:xx@tcp(127.0.0.1:3306)/test?charset=utf8")
	if err != nil {
		return nil, errors.Wrap(err, "open db error")
	}

	defer db.Close()

	user := User{}
	err = db.QueryRow("SELECT id,name,age FROM user WHERE id=?", id).Scan(
		&user.Id, &user.Name, &user.Age,
	)
	if err != nil && err == sql.ErrNoRows {
		return nil, nil
	} else if err != nil {
		return nil, errors.Wrap(err, "query row error")
	}
	return &user, nil
}
